/**
 * 
 */
package cc.rico.jms.p2p.consumer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import cc.rico.jms.p2p.listener.QueueMessageListener;
import cc.rico.jms.utils.ActiveMQConnectionUtils;

/**
 * @author rico 2016年8月2日
 *
 */
public class SimpleConsumer {
	private Connection connection;  
    private Session session;  
    private MessageConsumer consumer;  
    private boolean isStarted = true;
    
    public SimpleConsumer() {
		try {
			//ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.223.137:61616");
			//connection = connectionFactory.createConnection();
			connection = ActiveMQConnectionUtils.createQueueConnection();
			
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue("queue1");
			
			consumer = session.createConsumer(destination);
			consumer.setMessageListener(new QueueMessageListener(session, 1));
			
			//MessageConsumer consumer1 = session.createConsumer(destination);
			//consumer1.setMessageListener(new QueueMessageListener(session, 2));
			
			connection.start();
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
    }
    
    public synchronized boolean start() {
    	if(isStarted){  
            return true;  
        }  
    	
        try{  
            connection.start();  
            isStarted = true;  
            return true;  
        }catch(Exception e){  
            return false;  
        }  
    }
    
    
    public synchronized void close() {
    	if(isStarted) {
    		isStarted = false;
    		
    		try {
				session.close();
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
    	}
    }
    
}
